package bb.lanxing.activity.routebook;

import static bb.lanxing.common.config.Constants.REQUEST_CODE;
import static bb.lanxing.manager.SPConstant.KEY_LU_SHU;
import static bb.lanxing.manager.SPConstant.KEY_SERVER_ID;
import static bb.lanxing.manager.SPConstant.KEY_SHOW_IMPORT_LUSHU;
import static bb.lanxing.model.database.PostQueue.TYPE_LUSHU_COMMENT;
import static bb.lanxing.view.ShareView.TYPE_OTHER;
import static bb.lanxing.view.ShareView.TYPE_WECHAT;
import static bb.lanxing.view.ShareViewHorizontal.TYPE_WX_CIRCLE;

import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson.JSON;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.activity.sport.SportBeforeActivity;
import bb.lanxing.ali.behavior.AppBehavior;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.databinding.ActivityRouteInfoBinding;
import bb.lanxing.databinding.LayoutCommentCollapsedRouteInfoBinding;
import bb.lanxing.databinding.sprint.routebook.RouteBookInfoTitleHandle;
import bb.lanxing.manager.ShareDialogMgr;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.LevelHP;
import bb.lanxing.model.database.PostQueue;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.event.RouteBookEvent;
import bb.lanxing.model.json.Comment;
import bb.lanxing.model.json.RouteBookComment;
import bb.lanxing.model.json.ServerUser;
import bb.lanxing.model.json.TrackSegment;
import bb.lanxing.model.json.UserAvatarMedal;
import bb.lanxing.model.json.level.RuleConsume;
import bb.lanxing.mvp.presetner.RouteBookInfoPresenterImpl;
import bb.lanxing.mvp.presetner.i.IRouteBookInfoPresenter;
import bb.lanxing.mvp.view.adapter.RouteBookInfoAdapter;
import bb.lanxing.mvp.view.i.IRouteInfoView;
import bb.lanxing.service.PostQueueService;
import bb.lanxing.util.BusProvider;
import bb.lanxing.util.CustomShareUtil;
import bb.lanxing.util.LushuStyleUtils;
import bb.lanxing.util.MedalUtil;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.SportTypeResUtil;
import bb.lanxing.util.UserAvatarUtil;
import bb.lanxing.util.text.TextUtils;
import bb.lanxing.util.ui.ILoadableView;
import bb.lanxing.util.ui.RecyclerViewLoadingHelper;
import bb.lanxing.utils.IntentUtils;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.CommentViewHelper;
import bb.lanxing.view.ShareView;

public class RouteBookInfoActivity extends BaseActivity implements IRouteInfoView, CommentViewHelper.CommentActionListener, ILoadableView, BesServiceListener, DialogInterface.OnCancelListener {
	public static final int COLLECTION_TYPE_CANCEL = 1;
	public static final int COLLECTION_TYPE_COLLECT = 0;
	public static final int REQUEST_TYPE_ROUTE_BOOK_COMMENT = 1;
	public static final int REQUEST_TYPE_ROUTE_BOOK_INFO = 4;
	private static final String TAG = "RouteInfoActivity";
	private static final int LAUNCH_MODE_NONE = 0;
	private static final int LAUNCH_MODE_DETAIL_INFO = 1;
	private static final int LAUNCH_MODE_EDIT = 2;
	ProtocolService protocolService = null;
	private RouteBookInfoAdapter adapter;
	private RouteBookComment commentAt;
	private CommentViewHelper commentViewHelper;
	private MenuItem editMenu;
	private ActivityRouteInfoBinding infoBinding;
	private List<RouteBookComment> localComments;
	private RouteBook mRouteBook;
	private List<RouteBookComment> routeBookCommentList;
	private ShareDialogMgr mShareDialogMgr;
	private IRouteBookInfoPresenter presenter;
	private final BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override public void onReceive(Context context, Intent intent) {
			PostQueue postQueue;
			String action = intent.getAction();
			if (PostQueueService.ACTION_SEND_POST_SUCCEED.equals(action)) {
				PostQueue postQueue2 = intent.getParcelableExtra(PostQueueService.EXTRA_POST_DATA);
				if (postQueue2 == null || postQueue2.getType() != TYPE_LUSHU_COMMENT || mRouteBook == null || mRouteBook.getServerId() != postQueue2.getSubId()) {
					return;
				}
				presenter.requestRouteComment(mRouteBook, true);
			} else if (PostQueueService.ACTION_SEND_POST_FAILED.equals(action) && (postQueue = intent.getParcelableExtra(PostQueueService.EXTRA_POST_DATA)) != null && postQueue.getType() == TYPE_LUSHU_COMMENT) {
				if (mRouteBook == null || mRouteBook.getServerId() == postQueue.getSubId()) {
					showCommentFailed(postQueue);
				}
			}
		}
	};
	private RecyclerViewLoadingHelper recyclerViewLoadingHelper;
	private LayoutCommentCollapsedRouteInfoBinding viewBinding;
	private boolean mIsSharing = false;
	private final ShareView.ShareItemClickListener mShareItemClickListener = type -> {
		if (mIsSharing) {
			return;
		}
		mIsSharing = true;
		CustomShareUtil.shareLuShu(this, mRouteBook, type);
		mIsSharing = false;
		mShareDialogMgr.hide();
		publishShareEvent(type);
	};
	private String traceId = null;
	private boolean showImportLushu = false;

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.traceId = getIntent().getStringExtra("trace_id");
		long lushuId = getIntent().getLongExtra(SportActivity.EXTRA_LUSHU_ID, -1L);
		showImportLushu = getIntent().getBooleanExtra(KEY_SHOW_IMPORT_LUSHU, false);
		Log.d(TAG, "RouteInfoActivity onCreate lushuId: " + lushuId);
		if (lushuId < 0) {
			this.mRouteBook = getIntent().getParcelableExtra(KEY_LU_SHU);
		} else {
			this.mRouteBook = RouteBook.getById(lushuId);
		}
		if (this.mRouteBook == null) {
			long serverId = getIntent().getLongExtra(KEY_SERVER_ID, 0);
			if (serverId > 0) {
				RouteBook routeBook = new RouteBook();
				this.mRouteBook = routeBook;
				routeBook.setServerId(serverId);
			} else {
				App.getContext().showMessage(R.string.lushu_toast_no_lushu);
				finish();
				return;
			}
		}
		LushuStyleUtils.applyTheme(this, mRouteBook != null ? mRouteBook.getStyle() : 0);
		infoBinding = DataBindingUtil.setContentView(this, R.layout.activity_route_info);
		init();
		if (showImportLushu) {
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			protocolPresenter.setProtocolServiceListener(this);
			protocolService = protocolPresenter.getProtocolService();
			protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_ROUTE_BOOKS_INFO, SettingsJsonUtils.getDeviceModel(this), SettingsJsonUtils.getSn(this));
		}
	}

	public void init() {
		initView();
		initAdapter();
		initAdapterClick();
		initBroadCastRegister();
		initShareDialog();
		initCommentInput();
	}

	public void initView() {
		setupActionBar(true, -1, true, false);
		this.presenter = new RouteBookInfoPresenterImpl(this);
		this.routeBookCommentList = new ArrayList<>();
		this.localComments = new LinkedList<>();
		MobclickAgent.onEventValue(this, UmengEventConst.LUSHU_DETAIL, null, 1);
		this.infoBinding.refreshView.setOnRefreshListener(() -> presenter.requestRouteComment(mRouteBook, true));
		this.presenter.readCommentsFromCache(this.mRouteBook);
	}

	public void initAdapter() {
		this.adapter = new RouteBookInfoAdapter(this.mRouteBook, this);
		this.infoBinding.listView.setLayoutManager(new LinearLayoutManager(this));
		this.infoBinding.listView.setAdapter(RecyclerViewLoadingHelper.wrap(this.adapter));
		if (this.mRouteBook.getServerId() > 0) {
			if (!LushuStyleUtils.isFromApplyTheme(this)) {
				autoRefresh();
				this.presenter.requestRouteInfo(this.mRouteBook, false, LAUNCH_MODE_NONE);
			}
			if (getIntent().getBooleanExtra("search_click", false)) {
				AppBehavior.route().searchClick().trace(this.traceId).item(String.valueOf(this.mRouteBook.getServerId())).submit();
			} else {
				AppBehavior.route().click().trace(this.traceId).item(String.valueOf(this.mRouteBook.getServerId())).submit();
			}
		} else {
			ViewGroup.LayoutParams layoutParams = this.infoBinding.listView.getLayoutParams();
			layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
			layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
			if (!ViewCompat.isInLayout(this.infoBinding.listView)) {
				this.infoBinding.listView.setLayoutParams(layoutParams);
			}
			if (this.adapter.getHeaderBinding() != null) {
				this.adapter.getHeaderBinding().isEmptyView.setVisibility(View.VISIBLE);
			}
		}
		RecyclerViewLoadingHelper recyclerViewLoadingHelper = new RecyclerViewLoadingHelper(this);
		this.recyclerViewLoadingHelper = recyclerViewLoadingHelper;
		recyclerViewLoadingHelper.attachToRecyclerView(this.infoBinding.listView);
	}

	public void initAdapterClick() {
		this.adapter.setCommentHandle(position -> {
			commentAt = adapter.getItem(position);
			commentViewHelper.commentAt(commentAt.getUserName());
		});
		this.adapter.setItemClickListener(this::showItemLongClickDialog);
		this.adapter.setRouteInfoTitleHandle(new RouteBookInfoTitleHandle() {
			@Override public void routeTitleClick() {
			}

			@Override public void show3DLushu(RouteBook routeBook) {
				IntentUtils.gotoWebBrowser(RouteBookInfoActivity.this, routeBook.getThreedLushu(), routeBook.getTitle(), true);
			}

			@Override public void onRouteUserClick(RouteBook routeBook) {
				UserAvatarUtil.getInstance().goToUserInfo(RouteBookInfoActivity.this, routeBook.getUserId());
			}

			@Override public void onSegmentUserItemClick(RouteBook routeBook) {
			}

			@Override public void onRouteDescClick(RouteBook routeBook) {
				if (TextUtils.isEmptyOrNull(routeBook.getDescription())) {
					return;
				}
				new BiciAlertDialogBuilder(RouteBookInfoActivity.this).setMessage(routeBook.getDescription()).show();
			}

			@Override public void onRouteDescMoreClick() {
				if (adapter.getHeaderBinding() != null) {
					boolean booleanValue = (Boolean) adapter.getHeaderBinding().routeDescriptionMore.getTag();
					adapter.getHeaderBinding().routeDescriptionMore.setImageResource(booleanValue ? R.drawable.ic_topic_plate_popup_drop : R.drawable.ic_topic_plate_popup_up);
					adapter.getHeaderBinding().routeCreateTime.setMaxLines(booleanValue ? 2 : 100);
					adapter.getHeaderBinding().routeDescriptionMore.setTag(Boolean.valueOf(!booleanValue));
				}
			}

			@Override public void onMapViewClick(RouteBook routeBook) {
				Objects.requireNonNull(routeBook, "lushu can't be null");
				if (routeBook.getId() == null) {
					checkStoragePermission();
				} else {
					gotoDetailInfo(routeBook);
				}
			}

			@Override public void showMedalDetail(int i) {
				TrackSegment trackSegment = mRouteBook.getTrackSegment();
				if (trackSegment != null) {
					UserAvatarMedal userAvatarMedal = trackSegment.getUserAvatarMedals().get(i);
					MedalUtil.showAvatorMedalDetail(RouteBookInfoActivity.this, userAvatarMedal.getMedalId(), userAvatarMedal.getMedalLevel());
				}
			}
		});
	}

	private void checkStoragePermission() {
		if (RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getStoragePermissions())) {
			this.presenter.requestRouteInfo(this.mRouteBook, true, LAUNCH_MODE_DETAIL_INFO);
		} else {
			showStoragePermissionDialog();
		}
	}

	private void showStoragePermissionDialog() {
		new BiciAlertDialogBuilder(this).setTitle(getString(R.string.permission_request_permission_tips)).setMessage(getResources().getString(R.string.permission_lushu_need_storage)).setCancelable(true).setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> requestStoragePermission()).setNegativeButton(R.string.skip, (dialog, which) -> {
		}).show();
	}

	public void requestStoragePermission() {
		RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getStoragePermissions()).permissionRequestEachCombined(this, new RxPermissionUtil.PermissionCallBack() {
			@Override public void deny() {
			}

			@Override public void granted() {
				if (!App.isManagersInit) {
					App.getContext().initManagersWithPermissions();
				}
				presenter.requestRouteInfo(mRouteBook, true, LAUNCH_MODE_DETAIL_INFO);
			}
		});
	}

	public void initBroadCastRegister() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(PostQueueService.ACTION_SEND_POST_SUCCEED);
		intentFilter.addAction(PostQueueService.ACTION_SEND_POST_FAILED);
		registerReceiver(this.receiver, intentFilter, Context.RECEIVER_EXPORTED);
	}

	public void initShareDialog() {
		mShareDialogMgr = new ShareDialogMgr(this);
		ShareView shareView = new ShareView(this);
		shareView.buildType(new int[] { TYPE_WECHAT, TYPE_WX_CIRCLE, TYPE_OTHER });
		shareView.setShareItemClickListener(this.mShareItemClickListener);
		mShareDialogMgr.setContent(shareView);
	}

	public void initCommentInput() {
		CommentViewHelper commentViewHelper = new CommentViewHelper(this, this, true);
		this.commentViewHelper = commentViewHelper;
		this.viewBinding = DataBindingUtil.bind(commentViewHelper.addCollapsedView(R.layout.layout_comment_collapsed_route_info));
		updateCommentCollectionState();
		viewBinding.routeControl.setOnClickListener((v) -> {
			if (mRouteBook.isNeedUpdate()) {
				presenter.requestRouteInfo(mRouteBook, true, LAUNCH_MODE_NONE);
			} else if (mRouteBook.getId() == null) {
				presenter.requestRouteInfo(mRouteBook, true, LAUNCH_MODE_NONE);
				AppBehavior.route().download().trace(traceId).item(String.valueOf(mRouteBook.getServerId())).submit();
			} else if (mRouteBook.getId() != null) {
				if (!mRouteBook.isDisplay()) {
					mRouteBook.setDisplay(true);
					mRouteBook.save();
				}
				startLushuForNav(mRouteBook);
				AppBehavior.route().use().item(String.valueOf(mRouteBook.getServerId())).trace(traceId).submit();
				RouteBookUtil.uploadRouteBookUseBehavior(mRouteBook.getServerId(), 5);
			} else {
				toast(R.string.lushu_info_download_first);
			}
		});
		viewBinding.routeCollectionControl.setOnClickListener((v) -> {
			if (!App.getContext().isUserSignin()) {
				App.getContext().userSignin();
			} else if (mRouteBook.getServerId() <= 0) {
				App.getContext().showMessage(R.string.lushu_info_upload_first);
			} else if (mRouteBook.isCollected()) {
				presenter.handleCollectRoute(mRouteBook, COLLECTION_TYPE_CANCEL);
				AppBehavior.route().uncollect().trace(traceId).item(String.valueOf(mRouteBook.getServerId())).submit();
			} else {
				MobclickAgent.onEventValue(RouteBookInfoActivity.this, UmengEventConst.LUSHU_COLLECTION, null, 1);
				presenter.handleCollectRoute(mRouteBook, COLLECTION_TYPE_COLLECT);
				AppBehavior.route().collect().trace(traceId).item(String.valueOf(mRouteBook.getServerId())).submit();
			}
		});
		viewBinding.routeImport.setOnClickListener((v) -> {
			this.presenter.downloadRoute(mRouteBook.getServerId());
		});
		viewBinding.routeImport.setVisibility(showImportLushu ? View.VISIBLE : View.GONE);
	}

	@Override public void onLoading() {
		presenter.requestRouteComment(mRouteBook, routeBookCommentList != null ? routeBookCommentList.size() : 0);
	}

	public void showCommentFailed(final PostQueue postQueue) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(R.string.post_queue_send_failed).setMessage(getString(R.string.post_queue_send_failed_comment, TextUtils.getLimitString(JSON.parseObject(postQueue.getContent(), Comment.class).getContent(), 5))).setCancelable(false).setPositiveButton(R.string.post_queue_send_failed_retry, (dialog, which) -> {
			if (postQueue.getId() != null) {
				PostQueueService.clearNotify(getApplicationContext(), postQueue.getId().intValue());
			}
			PostQueueService.sendData(getApplicationContext(), postQueue, null);
		}).setNegativeButton(R.string.post_queue_send_failed_give_up, (dialog, which) -> {
			if (postQueue.getId() != null) {
				PostQueueService.clearNotify(getApplicationContext(), postQueue.getId().intValue());
				PostQueueService.deleteData(getApplicationContext(), postQueue);
				postQueue.delete();
			}
			presenter.getPostQueue(mRouteBook.getServerId());
		}).show();
		alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(this, R.color.black));
		alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(this, R.color.black));
	}

	public void publishShareEvent(int type) {
		String str = "";
		if (type == 0) {
			str = UmengEventConst.V30_LUSHU_SHARE_QQ;
		} else if (type == 1) {
			str = UmengEventConst.V30_LUSHU_SHARE_QZONE;
		} else if (type == 2) {
			str = UmengEventConst.V30_LUSHU_SHARE_WECHAT;
		} else if (type == 3) {
			str = UmengEventConst.V30_LUSHU_SHARE_WECHAT_MOMENTS;
		} else if (type == 4) {
			str = UmengEventConst.V30_LUSHU_SHARE_WEIBO;
		} else if (type == 6) {
			str = UmengEventConst.V30_LUSHU_SHARE_SAVE;
		} else if (type == 7) {
			str = UmengEventConst.V30_LUSHU_SHARE_OTHER;
		}
		if (TextUtils.isEmptyOrNull(str)) {
			return;
		}
		MobclickAgent.onEventValue(getApplicationContext(), str, null, 1);
	}

	private void gotoDetailInfo(RouteBook routeBook) {
		Intent intent = new Intent(this, RouteBookDetailMapActivity.class);
		intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getId());
		startActivityForResult(intent, REQUEST_CODE);
	}

	public void showItemLongClickDialog(int position) {
		final RouteBookComment item = this.adapter.getItem(position);
		boolean itSelfComments = (item.getUserId() == App.getContext().getUserId());
		CharSequence[] stringId = (itSelfComments) ? new String[] { /* getString(R.string.comment_report), */getString(R.string.copy), getString(R.string.comment_delete) } : new String[] { /* getString(R.string.comment_report), */ getString(R.string.copy) };
		new BiciAlertDialogBuilder(this).setItems(stringId, (dialog, which) -> {
			// remove report
			if (which == 0) {
				ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
				if (clipboardManager != null) {
					clipboardManager.setPrimaryClip(ClipData.newPlainText(null, item.getContent()));
					toast(R.string.toast_comment_copy);
				}
			} else if (which == 1) {
				presenter.deleteRouteComment(mRouteBook.getServerId(), item.getId());
			}
		}).show();
	}

	public void showLoadLushuDialog(final RouteBook routeBook) {
		View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_lushu_added, new LinearLayout(this));
		final AlertDialog show = new BiciAlertDialogBuilder(this, R.style.AppTheme_NoBackground_AlertDialog).setView(inflate).show();
		inflate.findViewById(R.id.tvGoTo).setOnClickListener(v -> {
			startLushuForNav(routeBook);
			show.dismiss();
			MobclickAgent.onEventValue(getApplicationContext(), UmengEventConst.LUSHU_LOADING, null, 1);
		});
	}

	private void startLushuForNav(RouteBook routeBook) {
		Intent intent = new Intent(getApplicationContext(), SportBeforeActivity.class);
		intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getId());
		intent.putExtra(SportActivity.EXTRA_TYPE_SPORT, routeBook.getSport());
		intent.putExtra(SportActivity.EXTRA_TITLE, getString(SportTypeResUtil.getTypeTextRes(routeBook.getSport())));
		intent.putExtra(SportBeforeActivity.EXTRA_SHOW_ROUTE_PLAN, false);
		startActivity(intent);
	}

	private void editRouteBook(RouteBook routeBook) {
		Intent intent = new Intent(this, RouteBookEditActivity.class);
		intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getId());
		startActivityForResult(intent, REQUEST_CODE);
	}

	@Override public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_lushu_info, menu);
		this.editMenu = menu.findItem(R.id.menu_lushu_edit);
		RouteBook routeBook = this.mRouteBook;
		if (routeBook != null && routeBook.getUserId() == SharedManager.getInstance().getUserId()) {
			this.editMenu.setVisible(true);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {
		int itemId = item.getItemId();
		if (itemId == R.id.action_share) {
			MobclickAgent.onEventValue(this, UmengEventConst.SHARE_LUSHU, null, 1);
			if (App.getContext().getSigninUser() == null) {
				App.getContext().userSignin();
			} else if (!this.mShareDialogMgr.isShowing()) {
				this.mShareDialogMgr.show(true);
			}
		} else if (itemId == R.id.menu_lushu_edit) {
			RouteBook routeBook = this.mRouteBook;
			if (routeBook == null) {
				return false;
			}
			if (routeBook.getSimilarityNum() > 0) {
				new BiciAlertDialogBuilder(this).setTitle(R.string.str_lushu_cannot_edit_title).setMessage(R.string.str_lushu_cannot_edit_msg).setPositiveButton(R.string.confirm, null).show();
				return true;
			} else if (this.mRouteBook.getId() != null) {
				editRouteBook(this.mRouteBook);
			} else {
				this.presenter.requestRouteInfo(this.mRouteBook, true, LAUNCH_MODE_EDIT);
			}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override public void onRequestRouteInfoResult(@Nullable RouteBook routeBook, boolean downLoad, int launchMode) {
		if (null != routeBook) {
			Long id = routeBook.getId();
			Log.i("RouteInfoActivity", "onRequestRouteInfoResult id = " + id);
			RouteBookInfoAdapter routeBookInfoAdapter;
			MenuItem menuItem;
			if (LushuStyleUtils.shouldApplyTheme(this, routeBook.getStyle())) {
				Bundle bundle = new Bundle();
				bundle.putParcelable(KEY_LU_SHU, routeBook);
				LushuStyleUtils.applyThemeAndRestart(this, routeBook.getStyle(), bundle);
				return;
			}
			if ((routeBookInfoAdapter = this.adapter) != null) {
				this.mRouteBook = routeBook;
				routeBookInfoAdapter.updateTitleData(routeBook);
				this.viewBinding.notifyChange();
				updateCommentCollectionState();
				if (id != null && routeBook.isNeedUpdate()) {
					setResult(Constants.RESULT_CODE_LUSHU_EDIT);
				}
				if (routeBook.getUserId() == SharedManager.getInstance().getUserId() && (menuItem = this.editMenu) != null) {
					menuItem.setVisible(true);
				}
			}
			if (downLoad) {
				MobclickAgent.onEventValue(this, UmengEventConst.LUSHU_DOWNLOAD, null, 1);
				downloadRouteBookWithCheck(routeBook, launchMode);
			}
		}
	}

	private void downloadRouteBookWithCheck(final RouteBook routeBook, final int launchMode) {
		// TODO: 2024/6/4 暂时移除等级校验, author:sunjw
		Long id = routeBook.getId();
		Log.i("RouteInfoActivity", "downloadRouteBookWithCheck id = " + id);
		// if (lushu.isDownload() || LevelPermissionMgr.getInstance().checkPermission(18)) {
		this.presenter.downloadRoute(routeBook, launchMode, false);
		// } else {
		// showCreditsDialog(lushu, launchMode);
		// }
	}

	public void showCreditsDialog(final RouteBook routeBook, final int launchMode) {
		new BiciAlertDialogBuilder(this).setMessage(R.string.str_lushu_download_need_credit).setPositiveButton(R.string.dialog_btn_ok, (dialog, which) -> presenter.downloadRoute(routeBook, launchMode, true)).setNegativeButton(R.string.dialog_btn_cancel, null).show();
	}

	@Override public void onDownLoadRouteResult(RouteBook routeBook, boolean needCredits, int launchMode) {
		setResult(Constants.RESULT_CODE_LUSHU_EDIT);
		processPermissionResponse(routeBook, needCredits, launchMode);
		App.getContext().sendBroadcast(new Intent(RouteBook.ACTION_DOWNLOAD_LUSHU));
		RouteBookUtil.showDialogForDownloadedRouteBook(this);
	}

	public void processPermissionResponse(RouteBook routeBook, boolean needCredits, int launchMode) {
		LevelHP levelHP = null;
		RuleConsume ruleConsume = null;
		if (routeBook != null && routeBook.getId() != null) {
			this.mRouteBook = routeBook;
			updateCommentCollectionState();
			if (launchMode == LAUNCH_MODE_DETAIL_INFO) {
				this.viewBinding.notifyChange();
				gotoDetailInfo(routeBook);
				return;
			} else if (launchMode == LAUNCH_MODE_EDIT) {
				editRouteBook(routeBook);
				return;
			} else {
				String string = getString(R.string.mine_level_toast_download_lushu_successful);
				// TODO: 2024/6/5 需要积分下载,author:sunjw
				// if (needCredits) {
				// if (LevelPermissionMgr.getInstance().getRule().getRuleConsume() != null) {
				// string = string + getString(R.string.mine_level_toast_consume_credits,
				// ruleConsume.getLushuDownload());
				// }
				// } else {
				// if (!lushu.isDownload()) {
				// LevelPermissionMgr.getInstance().updatePermisstion(18);
				// }
				// if (LevelPermissionMgr.getInstance().getLevelHP() != null) {
				// string = string + getString(R.string.mine_level_toast_consume_count, levelHP.getLushuDownload());
				// }
				// }
				App.getContext().showMessage(string);
				this.presenter.requestRouteInfo(routeBook, false, LAUNCH_MODE_NONE);
				return;
			}
		}
		App.getContext().showMessage(R.string.mine_level_toast_download_lushu_failed);
	}

	@Override public void onRequestRouteCommentResult(List<RouteBookComment> routeBookComments, RouteBook routeBook, boolean needClean) {
		if (needClean) {
			this.routeBookCommentList.clear();
		}
		this.routeBookCommentList.addAll(routeBookComments);
		if (adapter != null) {
			adapter.updateCommentData(routeBookComments, needClean);
		}
		this.localComments.clear();
		if (!routeBookComments.isEmpty() && (routeBookComments.get(0).getTime() == -2 || routeBookComments.get(0).getTime() == -1)) {
			this.localComments.add(0, routeBookComments.get(0));
		}
		updateNoneState();
		if (recyclerViewLoadingHelper != null) {
			recyclerViewLoadingHelper.complete();
			this.recyclerViewLoadingHelper.setEnabled(!routeBookComments.isEmpty());
		}
	}

	private void updateNoneState() {
		if (adapter.getItemCount() == 1) {
			ViewGroup.LayoutParams layoutParams = this.infoBinding.listView.getLayoutParams();
			layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
			layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
			if (!ViewCompat.isInLayout(this.infoBinding.listView)) {
				this.infoBinding.listView.setLayoutParams(layoutParams);
			}
			if (this.adapter.getHeaderBinding() != null) {
				this.adapter.getHeaderBinding().isEmptyView.setVisibility(View.VISIBLE);
				this.adapter.getHeaderBinding().commentCountLine.setVisibility(View.GONE);
			}
			return;
		}
		ViewGroup.LayoutParams layoutParams2 = this.infoBinding.listView.getLayoutParams();
		layoutParams2.width = ViewGroup.LayoutParams.MATCH_PARENT;
		layoutParams2.height = ViewGroup.LayoutParams.MATCH_PARENT;
		if (!ViewCompat.isInLayout(this.infoBinding.listView)) {
			this.infoBinding.listView.setLayoutParams(layoutParams2);
		}
		if (this.adapter.getHeaderBinding() != null) {
			this.adapter.getHeaderBinding().isEmptyView.setVisibility(View.GONE);
			this.adapter.getHeaderBinding().commentCountLine.setVisibility(View.VISIBLE);
		}
	}

	@Override public void onRouteCommentDeleteResult(boolean result) {
		if (result) {
			dismissLoadingDialog();
			toast(R.string.toast_comment_delete_on_successful);
			autoRefresh();
			this.presenter.requestRouteInfo(this.mRouteBook, false, LAUNCH_MODE_NONE);
		}
	}

	@Override public void onSendCommentNegativeResult(List<PostQueue> postQueues) {
		for (RouteBookComment routeBookComment : this.localComments) {
			this.adapter.delete(routeBookComment);
		}
		this.localComments.clear();
		if (postQueues == null || postQueues.isEmpty()) {
			return;
		}
		for (int i = 0; i < postQueues.size(); i++) {
			PostQueue postQueue = postQueues.get(i);
			RouteBookComment routeBookComment2 = JSON.parseObject(postQueue.getContent(), RouteBookComment.class);
			routeBookComment2.setTime(postQueue.getState() == 2 ? -2L : -1L);
			this.localComments.add(0, routeBookComment2);
		}
		this.adapter.insertComment(0, this.localComments.get(0));
	}

	@Override public void handleCollectionResult(boolean result, int type, RouteBook routeBook) {
		if (result) {
			if (type == COLLECTION_TYPE_COLLECT) {
				BusProvider.getInstance().post(new RouteBookEvent(2, routeBook.getServerId()));
				App.getContext().showMessage(R.string.toast_collect_successful);
				routeBook.setCollectCount(routeBook.getCollectCount() + 1);
				routeBook.setIsCollected(true);
				RouteBookUtil.showDialogForCollectedRouteBook(this);
			} else if (type == COLLECTION_TYPE_CANCEL) {
				BusProvider.getInstance().post(new RouteBookEvent(1, routeBook.getServerId()));
				App.getContext().showMessage(R.string.toast_collect_cancel);
				int collectCount = routeBook.getCollectCount() - 1;
				if (collectCount < 0) {
					collectCount = 0;
				}
				routeBook.setCollectCount(collectCount);
				routeBook.setIsCollected(false);
			}
			setResult(Constants.RESULT_CODE_LUSHU_EDIT);
			this.presenter.requestRouteInfo(routeBook, false, LAUNCH_MODE_NONE);
		}
		updateCommentCollectionState();
	}

	@Override public void autoRefresh() {
		presenter.requestRouteComment(mRouteBook, true);
	}

	@Override public void refreshComplete() {
		this.infoBinding.refreshView.setRefreshing(false);
	}

	@Override public void onSend(CharSequence editable, List<String> imageList) {
		if (!App.getContext().isUserSignin()) {
			App.getContext().userSignin();
			return;
		}
		if (this.mRouteBook.getServerId() <= 0) {
			App.getContext().showMessage(R.string.lushu_info_upload_first);
			return;
		}
		String trim = editable.toString().trim();
		if (android.text.TextUtils.isEmpty(trim)) {
			toast(R.string.topic_create_toast_content_empty);
			return;
		}
		RouteBookComment routeBookComment = this.commentAt;
		long userId = routeBookComment != null ? routeBookComment.getUserId() : 0L;
		ServerUser buildCurrentUser = PostQueue.buildCurrentUser();
		RouteBookComment routeBookComment2 = new RouteBookComment();
		routeBookComment2.setContent(trim);
		routeBookComment2.setInformedUserId(userId);
		routeBookComment2.setTime(-1L);
		routeBookComment2.setUserId(buildCurrentUser.getUserId());
		routeBookComment2.setLevel(buildCurrentUser.getLevel());
		routeBookComment2.setPlateNum(buildCurrentUser.getPlateNum());
		routeBookComment2.setMedalSmall(buildCurrentUser.getMedalSmall());
		routeBookComment2.setUserName(buildCurrentUser.getName());
		routeBookComment2.setUserPic(buildCurrentUser.getPhotoUrl());
		if (imageList != null && !imageList.isEmpty()) {
			StringBuilder str = new StringBuilder();
			for (String s : imageList) {
				str.append("file://").append(s).append(";");
			}
			routeBookComment2.setImageUrl(str.substring(0, str.length() - 1));
		}
		PostQueueService.sendData(getApplicationContext(), new PostQueue(this.mRouteBook.getServerId(), TYPE_LUSHU_COMMENT, JSON.toJSONString(routeBookComment2)), imageList == null ? null : new ArrayList<>(imageList));
		this.localComments.add(routeBookComment2);
		this.adapter.insertComment(0, routeBookComment2);
		updateNoneState();
		AppBehavior.route().comment().trace(this.traceId).content(trim).item(String.valueOf(this.mRouteBook.getServerId())).submit();
	}

	@Override public void onCommentAtRemove() {
		this.commentAt = null;
	}

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		this.commentViewHelper.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_CANCELED) {
			setResult(resultCode);
		}
		if (resultCode == Constants.RESULT_CODE_LUSHU_EDIT) {
			this.presenter.queryRouteBook(this.mRouteBook, LAUNCH_MODE_NONE);
		} else if (resultCode == Constants.RESULT_CODE_LUSHU_COMMNET) {
			autoRefresh();
		} else if (resultCode == Constants.RESULT_CODE_LUSHU_DELETE) {
			finish();
		}
	}

	@Override public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(this.receiver);
		CommentViewHelper commentViewHelper = this.commentViewHelper;
		if (commentViewHelper != null) {
			commentViewHelper.deleteTemp();
		}
		IRouteBookInfoPresenter iRouteBookInfoPresenter = this.presenter;
		if (iRouteBookInfoPresenter != null) {
			iRouteBookInfoPresenter.destroy();
		}
		RecyclerViewLoadingHelper recyclerViewLoadingHelper = this.recyclerViewLoadingHelper;
		if (recyclerViewLoadingHelper != null) {
			recyclerViewLoadingHelper.detachFromRecyclerView(this.infoBinding.listView);
		}
	}

	private String getRouteControlText() {
		if (this.mRouteBook.getId() != null) {
			if (this.mRouteBook.isNeedUpdate()) {
				return getString(R.string.update);
			}
			return getString(R.string.lushu_info_use);
		}
		return String.valueOf(this.mRouteBook.getDownloadCount());
	}

	private String getCollectionCount() {
		int collectCount = this.mRouteBook.getCollectCount();
		int i = Math.max(collectCount, 0);
		return String.valueOf(i);
	}

	private Drawable getRouteControlIcon() {
		TypedArray obtainStyledAttributes = getTheme().obtainStyledAttributes(R.styleable.RouteBookStyle);
		Drawable drawableUse = obtainStyledAttributes.getDrawable(R.styleable.RouteBookStyle_styleRouteBookDetailUseDrawable);
		Drawable drawableDownload = obtainStyledAttributes.getDrawable(R.styleable.RouteBookStyle_styleRouteBookDetailDownloadDrawable);
		obtainStyledAttributes.recycle();
		return this.mRouteBook.getId() != null ? this.mRouteBook.isNeedUpdate() ? getResources().getDrawable(R.drawable.ic_update) : drawableUse : drawableDownload;
	}

	private Drawable getCollectionIcon() {
		TypedArray obtainStyledAttributes = getTheme().obtainStyledAttributes(R.styleable.RouteBookStyle);
		Drawable drawableCollection = obtainStyledAttributes.getDrawable(R.styleable.RouteBookStyle_styleRouteBookDetailCollectDrawable);
		Drawable drawableCancelCollection = obtainStyledAttributes.getDrawable(R.styleable.RouteBookStyle_styleRouteBookDetailUncollectDrawable);
		obtainStyledAttributes.recycle();
		return this.mRouteBook.isCollected() ? drawableCollection : drawableCancelCollection;
	}

	private void updateCommentCollectionState() {
		viewBinding.routeControl.setText(getRouteControlText());
		viewBinding.routeCollectionControl.setText(getCollectionCount());
		Drawable drawableDownload = getRouteControlIcon();
		Drawable drawableCollection = getCollectionIcon();
		drawableDownload.setBounds(0, 0, drawableDownload.getMinimumWidth(), drawableDownload.getMinimumHeight());
		drawableCollection.setBounds(0, 0, drawableCollection.getMinimumWidth(), drawableCollection.getMinimumHeight());
		viewBinding.routeControl.setCompoundDrawables(drawableDownload, null, null, null);
		viewBinding.routeCollectionControl.setCompoundDrawables(drawableCollection, null, null, null);
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {
	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {
	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		Log.d(TAG, " onSuccessMessage,msg: " + msg);
		if (msg == com.bes.sdk.message.Constants.TOTAL_ROUTE_FILES_ALL_TRANS_SUCCESS) {
			dismissLoadingDialog();
			runOnUiThread(() -> Toast.makeText(getActivity(), "Sync Route success", Toast.LENGTH_SHORT).show());
		}
	}

	@Override public void onCancel(DialogInterface dialog) {
		if (protocolService != null) {
			Log.d(TAG, " loading dialog on cancel,send give up trans file cmd");
			protocolService.bikewatch_send_giveup_trans_file(this);
		}
	}
}
